import type {
  ApiResponse,
  ApiErrorResponse,
  User,
  UserProfile,
  UserCreateData,
  UserUpdateData,
  UserListResponse,
  UserStats,
  KnowledgeBase,
  KnowledgeBaseCreateData,
  KnowledgeBaseUpdateData,
  KnowledgeBaseListResponse,
  KnowledgeBaseStats,
  Category,
  CategoryCreateData,
  CategoryUpdateData,
  CategoryReorderData,
  CategoryStats,
  Tag,
  TagCreateData,
  TagUpdateData,
  TagBatchCreateData,
  TagBatchDeleteData,
  TagListResponse,
  TagBatchResult,
  TagStats,
  FileInfo,
  FileListResponse,
  FileStats,
  SearchParams,
  SearchResponse,
  AnalyticsOverview,
  TrendData,
  TopContent,
  UserBehavior,
  ContentAnalysis,
  UserGrowth,
  LoginCredentials,
  RegisterData,
  AuthResponse,
  RefreshTokenData
} from './types'
import { clearUserCache, getTabToken } from './cache'

const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:4000/api'

// 通用请求函数
async function request<T>(
  endpoint: string,
  options: RequestInit = {}
): Promise<ApiResponse<T> | ApiErrorResponse> {
  const url = `${API_BASE_URL}${endpoint}`
  
  const config: RequestInit = {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
    ...options,
  }

  // 添加认证token
  const token = getTabToken()
  if (token) {
    config.headers = {
      ...config.headers,
      'Authorization': `Bearer ${token}`
    }
  }

  try {
    const response = await fetch(url, config)
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}))
      throw new Error(errorData.error || errorData.message || `HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    
    // 支持新的响应格式 (code: 200) 和旧的格式 (success: true)
    if (data.code === 200) {
      return data as ApiResponse<T>
    } else if (data.success === true || data.success === false) {
      return data as ApiErrorResponse
    } else {
      return data as ApiResponse<T>
    }
  } catch (error) {
    console.error('API request failed:', error)
    throw error
  }
}

// 认证相关接口
export const authAPI = {
  // 登录
  login: async (credentials: LoginCredentials): Promise<AuthResponse> => {
    const response = await request<{ user: User; token: string }>('/auth/login', {
      method: 'POST',
      body: JSON.stringify(credentials),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('登录失败')
  },

  // 注册
  register: async (userData: RegisterData): Promise<AuthResponse> => {
    const response = await request<{ user: User; token: string }>('/auth/register', {
      method: 'POST',
      body: JSON.stringify(userData),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('注册失败')
  },

  // 刷新token
  refreshToken: async (token: string): Promise<AuthResponse> => {
    const response = await request<{ user: User; token: string }>('/auth/refresh', {
      method: 'POST',
      body: JSON.stringify({ token }),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('令牌刷新失败')
  },

  // 获取当前用户信息
  getCurrentUser: async (): Promise<UserProfile> => {
    const response = await request<{ user: UserProfile }>('/auth/me')
    
    if ('code' in response && response.code === 200) {
      return response.data.user
    }
    throw new Error('获取用户信息失败')
  },

  // 更新用户资料
  updateProfile: async (profileData: Partial<UserProfile>): Promise<UserProfile> => {
    const response = await request<UserProfile>('/auth/profile', {
      method: 'PUT',
      body: JSON.stringify(profileData),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('更新用户资料失败')
  },

  // 更新用户头像
  updateAvatar: async (avatarFile: File): Promise<{ avatar: string }> => {
    const formData = new FormData()
    formData.append('avatar', avatarFile)
    
    const token = localStorage.getItem('admin_token')
    
    const response = await fetch(`${API_BASE_URL}/auth/avatar`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
      },
      body: formData,
    })
    
    if (!response.ok) {
      throw new Error(`Avatar upload failed: ${response.status}`)
    }
    
    const result = await response.json()
    
    if ('code' in result && result.code === 200) {
      return result.data
    }
    throw new Error('头像上传失败')
  },

  // 登出
  logout: async (): Promise<void> => {
    const response = await request<null>('/auth/logout', { method: 'POST' })
    
    if ('code' in response && response.code === 200) {
      // 使用统一的缓存清理工具
      clearUserCache()
    }
  },
}

// 用户管理接口
export const usersAPI = {
  // 获取用户列表
  getUsers: async (params?: {
    page?: number
    limit?: number
    search?: string
    role?: string
    status?: string
  }): Promise<UserListResponse> => {
    const searchParams = new URLSearchParams()
    if (params) {
      Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined) searchParams.append(key, value.toString())
      })
    }
    
    const response = await request<UserListResponse>(`/users?${searchParams.toString()}`)
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取用户列表失败')
  },

  // 获取单个用户
  getUser: async (id: string): Promise<User> => {
    const response = await request<User>(`/users/${id}`)
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取用户信息失败')
  },

  // 创建用户
  createUser: async (userData: UserCreateData): Promise<User> => {
    const response = await request<User>('/users', {
      method: 'POST',
      body: JSON.stringify(userData),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('创建用户失败')
  },

  // 更新用户
  updateUser: async (id: string, userData: UserUpdateData): Promise<User> => {
    const response = await request<User>(`/users/${id}`, {
      method: 'PUT',
      body: JSON.stringify(userData),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('更新用户失败')
  },

  // 删除用户
  deleteUser: async (id: string): Promise<void> => {
    const response = await request<null>(`/users/${id}`, { method: 'DELETE' })
    
    if ('code' in response && response.code === 200) {
      return
    }
    throw new Error('删除用户失败')
  },

  // 重置用户密码
  resetPassword: async (id: string, newPassword: string): Promise<void> => {
    const response = await request<null>(`/users/${id}/reset-password`, {
      method: 'POST',
      body: JSON.stringify({ newPassword }),
    })
    
    if ('code' in response && response.code === 200) {
      return
    }
    throw new Error('重置密码失败')
  },

  // 获取用户统计信息
  getUserStats: async (): Promise<UserStats> => {
    const response = await request<UserStats>('/users/stats/overview')
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取用户统计失败')
  },
}

// 知识库管理接口
export const knowledgeAPI = {
  // 获取知识库列表
  getKnowledgeBases: async (params?: {
    page?: number
    limit?: number
    search?: string
    status?: string
    categoryId?: string
    tagIds?: string
    authorId?: string
    featured?: boolean
  }): Promise<KnowledgeBaseListResponse> => {
    const searchParams = new URLSearchParams()
    if (params) {
      Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined) searchParams.append(key, value.toString())
      })
    }
    
    const response = await request<KnowledgeBaseListResponse>(`/knowledge-base?${searchParams.toString()}`)
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取知识库列表失败')
  },

  // 获取单个知识库
  getKnowledgeBase: async (id: string): Promise<KnowledgeBase> => {
    const response = await request<KnowledgeBase>(`/knowledge-base/${id}`)
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取知识库详情失败')
  },

  // 创建知识库
  createKnowledgeBase: async (knowledgeData: KnowledgeBaseCreateData): Promise<KnowledgeBase> => {
    const response = await request<KnowledgeBase>('/knowledge-base', {
      method: 'POST',
      body: JSON.stringify(knowledgeData),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('创建知识库失败')
  },

  // 更新知识库
  updateKnowledgeBase: async (id: string, knowledgeData: KnowledgeBaseUpdateData): Promise<KnowledgeBase> => {
    const response = await request<KnowledgeBase>(`/knowledge-base/${id}`, {
      method: 'PUT',
      body: JSON.stringify(knowledgeData),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('更新知识库失败')
  },

  // 删除知识库
  deleteKnowledgeBase: async (id: string): Promise<void> => {
    const response = await request<null>(`/knowledge-base/${id}`, { method: 'DELETE' })
    
    if ('code' in response && response.code === 200) {
      return
    }
    throw new Error('删除知识库失败')
  },

  // 更新知识库状态
  updateKnowledgeBaseStatus: async (id: string, status: string): Promise<KnowledgeBase> => {
    const response = await request<KnowledgeBase>(`/knowledge-base/${id}/status`, {
      method: 'PATCH',
      body: JSON.stringify({ status }),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('更新知识库状态失败')
  },

  // 切换精选状态
  toggleFeatured: async (id: string, featured: boolean): Promise<KnowledgeBase> => {
    const response = await request<KnowledgeBase>(`/knowledge-base/${id}/featured`, {
      method: 'PATCH',
      body: JSON.stringify({ featured }),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('更新精选状态失败')
  },

  // 点赞/取消点赞
  toggleLike: async (id: string): Promise<{ liked: boolean }> => {
    const response = await request<{ liked: boolean }>(`/knowledge-base/${id}/like`, {
      method: 'POST',
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('点赞操作失败')
  },

  // 获取知识库统计信息
  getKnowledgeBaseStats: async (): Promise<KnowledgeBaseStats> => {
    const response = await request<KnowledgeBaseStats>('/knowledge/stats/overview')
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取知识库统计失败')
  },
}

// 分类管理接口
export const categoriesAPI = {
  // 获取分类列表
  getCategories: async (params?: { includeChildren?: boolean; includeStats?: boolean }): Promise<Category[]> => {
    const searchParams = new URLSearchParams()
    if (params) {
      Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined) searchParams.append(key, value.toString())
      })
    }
    
    const response = await request<Category[]>(`/categories?${searchParams.toString()}`)
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取分类列表失败')
  },

  // 获取分类树形结构
  getCategoryTree: async (): Promise<Category[]> => {
    const response = await request<Category[]>('/categories/tree')
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取分类树失败')
  },

  // 获取单个分类
  getCategory: async (id: string): Promise<Category> => {
    const response = await request<Category>(`/categories/${id}`)
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取分类详情失败')
  },

  // 创建分类
  createCategory: async (categoryData: CategoryCreateData): Promise<Category> => {
    const response = await request<Category>('/categories', {
      method: 'POST',
      body: JSON.stringify(categoryData),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('创建分类失败')
  },

  // 更新分类
  updateCategory: async (id: string, categoryData: CategoryUpdateData): Promise<Category> => {
    const response = await request<Category>(`/categories/${id}`, {
      method: 'PUT',
      body: JSON.stringify(categoryData),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('更新分类失败')
  },

  // 删除分类
  deleteCategory: async (id: string): Promise<void> => {
    const response = await request<null>(`/categories/${id}`, { method: 'DELETE' })
    
    if ('code' in response && response.code === 200) {
      return
    }
    throw new Error('删除分类失败')
  },

  // 批量更新分类排序
  reorderCategories: async (categories: CategoryReorderData[]): Promise<void> => {
    const response = await request<null>('/categories/reorder', {
      method: 'PATCH',
      body: JSON.stringify({ categories }),
    })
    
    if ('code' in response && response.code === 200) {
      return
    }
    throw new Error('更新分类排序失败')
  },

  // 获取分类统计信息
  getCategoryStats: async (): Promise<CategoryStats> => {
    const response = await request<CategoryStats>('/categories/stats/overview')
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取分类统计失败')
  },
}

// 标签管理接口
export const tagsAPI = {
  // 获取标签列表
  getTags: async (params?: {
    page?: number
    limit?: number
    search?: string
    sortBy?: string
    sortOrder?: string
  }): Promise<TagListResponse> => {
    const searchParams = new URLSearchParams()
    if (params) {
      Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined) searchParams.append(key, value.toString())
      })
    }
    
    const response = await request<TagListResponse>(`/tags?${searchParams.toString()}`)
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取标签列表失败')
  },

  // 获取所有标签（用于选择器）
  getAllTags: async (): Promise<Tag[]> => {
    const response = await request<Tag[]>('/tags/all')
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取所有标签失败')
  },

  // 获取单个标签
  getTag: async (id: string): Promise<Tag> => {
    const response = await request<Tag>(`/tags/${id}`)
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取标签详情失败')
  },

  // 创建标签
  createTag: async (tagData: TagCreateData): Promise<Tag> => {
    const response = await request<Tag>('/tags', {
      method: 'POST',
      body: JSON.stringify(tagData),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('创建标签失败')
  },

  // 批量创建标签
  createTagsBatch: async (tags: TagCreateData[]): Promise<TagBatchResult> => {
    const response = await request<TagBatchResult>('/tags/batch', {
      method: 'POST',
      body: JSON.stringify({ tags }),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('批量创建标签失败')
  },

  // 更新标签
  updateTag: async (id: string, tagData: TagUpdateData): Promise<Tag> => {
    const response = await request<Tag>(`/tags/${id}`, {
      method: 'PUT',
      body: JSON.stringify(tagData),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('更新标签失败')
  },

  // 删除标签
  deleteTag: async (id: string): Promise<void> => {
    const response = await request<null>(`/tags/${id}`, { method: 'DELETE' })
    
    if ('code' in response && response.code === 200) {
      return
    }
    throw new Error('删除标签失败')
  },

  // 批量删除标签
  deleteTagsBatch: async (tagIds: string[]): Promise<TagBatchResult> => {
    const response = await request<TagBatchResult>('/tags/batch', {
      method: 'DELETE',
      body: JSON.stringify({ tagIds }),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('批量删除标签失败')
  },

  // 获取标签统计信息
  getTagStats: async (): Promise<TagStats> => {
    const response = await request<TagStats>('/tags/stats/overview')
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取标签统计失败')
  },
}

// 文件管理接口
export const filesAPI = {
  // 获取文件列表
  getFiles: async (params?: {
    page?: number
    limit?: number
    search?: string
    type?: string
    userId?: string
  }): Promise<FileListResponse> => {
    const searchParams = new URLSearchParams()
    if (params) {
      Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined) searchParams.append(key, value.toString())
      })
    }
    
    const response = await request<FileListResponse>(`/upload?${searchParams.toString()}`)
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取文件列表失败')
  },

  // 上传文件
  uploadFile: async (file: File): Promise<FileInfo> => {
    const formData = new FormData()
    formData.append('file', file)
    
    const token = localStorage.getItem('admin_token')
    
    const response = await fetch(`${API_BASE_URL}/upload/single`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${token}`,
      },
      body: formData,
    })
    
    if (!response.ok) {
      throw new Error(`Upload failed: ${response.status}`)
    }
    
    const result = await response.json()
    
    if ('code' in result && result.code === 200) {
      return result.data
    }
    throw new Error('文件上传失败')
  },

  // 删除文件
  deleteFile: async (id: string): Promise<void> => {
    const response = await request<null>(`/upload/${id}`, { method: 'DELETE' })
    
    if ('code' in response && response.code === 200) {
      return
    }
    throw new Error('删除文件失败')
  },

  // 获取文件统计信息
  getFileStats: async (): Promise<FileStats> => {
    const response = await request<FileStats>('/upload/stats/overview')
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取文件统计失败')
  },
}

// 搜索接口
export const searchAPI = {
  // 全局搜索
  globalSearch: async (params: SearchParams): Promise<SearchResponse> => {
    const response = await request<SearchResponse>('/search', {
      method: 'POST',
      body: JSON.stringify(params),
    })
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('搜索失败')
  },

  // 获取搜索建议
  getSearchSuggestions: async (query: string): Promise<string[]> => {
    const response = await request<string[]>(`/search/suggestions?q=${encodeURIComponent(query)}`)
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取搜索建议失败')
  },

  // 获取热门搜索
  getHotSearches: async (): Promise<string[]> => {
    const response = await request<string[]>('/search/hot')
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取热门搜索失败')
  },

  // 获取搜索统计
  getSearchStats: async (timeRange: string): Promise<any> => {
    const response = await request<any>(`/search/stats?timeRange=${timeRange}`)
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取搜索统计失败')
  },
}

// 数据分析接口
export const analyticsAPI = {
  // 获取概览数据
  getOverview: async (): Promise<AnalyticsOverview> => {
    const response = await request<AnalyticsOverview>('/analytics/overview')
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取概览数据失败')
  },

  // 获取趋势数据
  getTrends: async (timeRange: string): Promise<TrendData[]> => {
    const response = await request<TrendData[]>(`/analytics/trends?timeRange=${timeRange}`)
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取趋势数据失败')
  },

  // 获取热门内容
  getTopContent: async (): Promise<TopContent[]> => {
    const response = await request<TopContent[]>('/analytics/top-content')
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取热门内容失败')
  },

  // 获取用户行为数据
  getUserBehavior: async (): Promise<UserBehavior> => {
    const response = await request<UserBehavior>('/analytics/user-behavior')
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取用户行为数据失败')
  },

  // 获取搜索统计
  getSearchStats: async (timeRange: string): Promise<any> => {
    const response = await request<any>(`/analytics/search-stats?timeRange=${timeRange}`)
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取搜索统计失败')
  },

  // 获取内容分析
  getContentAnalysis: async (timeRange: string): Promise<ContentAnalysis> => {
    const response = await request<ContentAnalysis>(`/analytics/content-analysis?timeRange=${timeRange}`)
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取内容分析失败')
  },

  // 获取用户增长数据
  getUserGrowth: async (timeRange: string): Promise<UserGrowth> => {
    const response = await request<UserGrowth>(`/analytics/user-growth?timeRange=${timeRange}`)
    
    if ('code' in response && response.code === 200) {
      return response.data
    }
    throw new Error('获取用户增长数据失败')
  },
}

export default {
  auth: authAPI,
  users: usersAPI,
  knowledge: knowledgeAPI,
  categories: categoriesAPI,
  tags: tagsAPI,
  files: filesAPI,
  search: searchAPI,
  analytics: analyticsAPI,
}
